<template>
  <div>
    <Bread1 :breadtitle="breadtitle"></Bread1>
    <a-alert message="添加商品信息" type="info" show-icon />

    <!-- 进度条 -->
    <a-steps class="steps" :current="activeIndex - 0" size="small">
      <a-step title="基本信息" />
      <a-step title="商品参数" />
      <a-step title="商品属性" />
      <a-step title="商品图片" />
      <a-step title="商品内容" />
      <a-step title="完成" />
    </a-steps>

    <!-- tabs便签 -->
    <a-form-model
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      ref="ruleForm"
      :model="addForm"
      :rules="addFormRules"
    >
      <a-tabs
        style="margin-top: 30px"
        v-model="activeIndex"
        tabPosition="left"
        @change="tabChange"
        @click="tabClicked"
      >
        <!-- 基本信息 -->
        <a-tab-pane key="0" tab="基本信息">
          <a-form-model-item has-feedback label="商品名称" prop="goods_name">
            <a-input autocomplete="off" v-model="addForm.goods_name" />
          </a-form-model-item>
          <a-form-model-item has-feedback label="商品价格" prop="goods_price">
            <a-input
              autocomplete="off"
              type="number"
              v-model="addForm.goods_price"
            />
          </a-form-model-item>
          <a-form-model-item has-feedback label="商品重量" prop="goods_weight">
            <a-input
              autocomplete="off"
              type="number"
              v-model="addForm.goods_weight"
            />
          </a-form-model-item>
          <a-form-model-item has-feedback label="商品数量" prop="goods_number">
            <a-input
              autocomplete="off"
              type="number"
              v-model="addForm.goods_number"
            />
          </a-form-model-item>
          <a-form-model-item has-feedback label="商品分类" prop="goods_cat">
            <a-tree-select
              v-model="addForm.goods_cat"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="catelist"
              placeholder="Please select"
              @change="handleChange"
              :replaceFields="{
                title: 'cat_name',
                children: 'children',
                value: 'cat_id',
                key: 'cat_id',
              }"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-tab-pane>

        <!-- 商品参数 -->
        <a-tab-pane key="1" tab="商品参数">
          <a-alert class="alert_list2" message="请在分类参数中修改 !" banner />
          <a-list :grid="{ gutter: 16 }" :data-source="manyTableData">
            <a-list-item
              slot="renderItem"
              ref="currentItem"
              slot-scope="item, index"
            >
              <a-card :title="item.attr_name">
                <a-checkbox-group
                  disabled
                  v-model="item.attr_vals"
                  :defaultValue="item.attr_vals"
                  :options="item.attr_vals"
                  @change="onChange(index)"
                />
              </a-card>
            </a-list-item>
          </a-list>
        </a-tab-pane>

        <!-- 商品属性 -->
        <a-tab-pane key="2" tab="商品属性">
          <a-form-item
            :label-col="{ span: 3 }"
            has-feedback
            :label="item.attr_name"
            v-for="item in onlyTableData"
            :key="item.attr_id"
          >
            <a-input autocomplete="off" v-model="item.attr_vals" />
          </a-form-item>
        </a-tab-pane>

        <a-tab-pane key="3" tab="商品图片">
          <a-upload
            action="http://124.223.60.155:8889/api/private/v1/upload"
            :headers="headerObj"
            list-type="picture"
          >
            <a-button> <a-icon type="upload" /> 上传图片 </a-button>
          </a-upload>
        </a-tab-pane>

        <!-- 商品内容 -->
        <a-tab-pane key="4" tab="商品内容">
          <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce" />
          <a-button class="subt" type="primary" @click="add">
            完成添加
          </a-button>
        </a-tab-pane>
      </a-tabs>
    </a-form-model>
  </div>
</template>

<script>
// import _ from "lodash";
import { reqCateList, reqDyOrSt,reqaddshop } from "@/api";
import Bread1 from "@/components/bread/Bread1";
export default {
  data() {
    return {
      labelCol: { span: 2 },
      wrapperCol: { span: 10 },
      breadtitle: ["商品管理", "商品列表", "添加商品"],
      //   steps索引
      activeIndex: "0",
      //添加商品参数
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      //   表单验证
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      //三级分类数据
      catelist: [],
      // 存储动态参数列表
      manyTableData: [],
      // 存储静态数据列表
      onlyTableData: [],
      // 请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
    };
  },
  components: { Bread1 },
  created() {
    //   调用获取三级分类方法
    this.getCateList();
  },
  methods: {
    //获取三级分类数据方法
    async getCateList() {
      let res = await reqCateList();
      //   console.log(res);
      if (res.meta.status === 200) {
        this.catelist = res.data;
      }
    },
    //三级选中
    handleChange(value, label, extra) {
      if (extra.triggerNode.$children.length > 0) {
        this.addForm.goods_cat = [];
        this.$message.warning("请选择三级菜单！");
        return;
      }
      let arr = [];
      arr.push(value);
      if (extra.triggerNode.$parent.value) {
        arr.push(extra.triggerNode.$parent.value);
      }
      if (extra.triggerNode.$parent.$parent.value) {
        arr.push(extra.triggerNode.$parent.$parent.value);
      }
      arr.sort();
      this.addForm.goods_cat = arr;
    },
    // tab切换
    tabChange(activeKey) {
      // console.log(activeKey);
      if (activeKey !== "0" && this.addForm.goods_cat.length !== 3) {
        this.activeIndex = "0";
        this.$message.warning("请先完成步骤一");
      }
    },
    // tab被点击的时候
    async tabClicked() {
      if (this.activeIndex === "1") {
        let res = await reqDyOrSt(this.addForm.goods_cat[2], "many");
        if (res.meta.status == 200) {
          res.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          });
          this.manyTableData = res.data;
        }
      }
      if (this.activeIndex === "2") {
        let res = await reqDyOrSt(this.addForm.goods_cat[2], "only");
        if (res.meta.status == 200) {
          // console.log(res);
          this.onlyTableData = res.data;
        }
      }
    },
    // 复选框事件
    onChange(index) {
      console.log(index);
      // console.log(this.value);
    },
    // 图片预览
    // previewFile(file) {
    //   console.log("Your upload file:", file);
    // },
    // action="http://124.223.60.155:8889/api/private/v1/upload"
    //         :headers="headerObj"

    // 添加商品
    add() {
      this.$refs.ruleForm.validate(async (valid) => {
        // console.log(valid);
        if (!valid) {
          return this.$message.warning("请完善表单内容！");
        }
        //执行添加的业务逻辑
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");
        // console.log(form)
        // 处理动态参数
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.onlyTableData.forEach((item) => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals };
          this.addForm.attrs.push(newInfo);
        });
        form.attrs = this.addForm.attrs;
        let res=await reqaddshop(form)
        console.log(res);
        if(res.meta.status!==201){
          return this.$message.warning("创建商品失败！");
        }
        this.$message.success('创建商品成功！')
      });
    },
  },
};
</script>

<style lang="less" scoped>
.steps {
  padding-top: 30px;
  width: 80%;
  margin: auto;
}
.alert_list2 {
  margin-bottom: 10px;
}
.subt {
  margin-top: 10px;
  float: right;
}
</style>